from os import path
import re
from urllib import request

from api.api_db import insert_file_path
from common.pd import SQL
from project.web_comm import add_token_to_url


# region 下载文件
def contains_illegal_char(filename):
    illegal_chars = ''.join(map(chr, range(32)))
    illegal_chars += '\\/:*?"<>|'
    illegal_chars += ''.join(map(chr, range(127, 256)))
    return any(char in illegal_chars for char in filename)


def remove_illegal_chars(file_name):
    new_filename = re.sub(r'[\/:*?"<>|]', '', file_name)

    return new_filename


def make_file_name_by_id(table_name: str, once_id: str):
    if "doc" in table_name:
        find_data_str = f'select file_name, title from {table_name} where once_id = "{once_id}"'

        sql = SQL()
        data = sql.find_one(find_data_str)
        if data:
            file_name = data[0] + "-" + data[1]
            return remove_illegal_chars(file_name)


def down_load_file(once_id, file_path):
    url_str = get_load_url(once_id)
    request.urlretrieve(url_str, file_path)


def download_file_to_save(dir_path, table_name, file_once_id):
    """根据文函的once_id 下载文件并保存文件信息到数据库"""
    file_name = make_file_name_by_id(table_name, file_once_id)
    file_path = path.join(dir_path, file_name)
    down_load_file(file_once_id, file_path+".pdf")
    if path.isfile(file_path):
        insert_file_path(file_path, table_name, file_once_id)


# endregion

# region 根据once_id 获取文件的相关地址
def get_read_url(once_id):
    """ 获取阅读文件查看的地址"""
    url_str = r"http://once/once/docviewer_mainFile?objectId=" + once_id

    return add_token_to_url(url_str)


def get_info_url(once_id):
    """ 获取阅读文件的详细信息地址"""
    url_str = r"http://once/once/docviewer?objectId=" + once_id
    return add_token_to_url(url_str)


def get_load_url(once_id):
    url = f"http://once/once/docdownload?objectId={once_id}"
    return add_token_to_url(url)


# endregion


# region  文件整理
"""
1）获取文件的名称
2）判断是文件还是函件
3）在数据库中查找文件
4）获取文件的once_id
5) 将文函放入指定的文件夹
6）将文件地址存放到file_path 数据表中
CREATE TABLE file_path (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    file_path    TEXT,
    is_invalid   INTEGER,
    file_type    TEXT,  # 文函的表名
    file_once_id TEXT   # 文函的once_id
);
"""


def get_file_info_by_name(file_path):
    directory, filename = path.split(file_path)
    file_name_with_ext, file_extension = path.splitext(file_path)
    is_fax = check_is_fax(filename)


def get_fax_channel(fax_name: str):
    fax_channel = None
    if len(fax_name) > 19:
        fax_info_list = fax_name.split("-")
        if len(fax_info_list[0]) == 2:
            fax_channel = fax_name[:19]
        if len(fax_info_list[0]) == 3:
            fax_channel = fax_name[:27]
    return fax_channel


def get_doc_channel(file_name):
    return file_name[0:29]


def check_is_fax(file_name):
    file_code = file_name[0:19]
    if "-" in file_code:
        return True
    else:
        return False


def check_is_doc(file_name):
    if len(file_name) >= 30:
        if "-" not in file_name[0:19] and file_name[19] == "-":
            return True
    return False
# endregion
